﻿using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

namespace XmlTypes
{
	using ParseFunc = System.Func<string,object>;
	public static class ParseBinder
	{
		/// <summary>
		/// 解析函数绑定字典,适用于已经定义的类型,在不更改其源代码的基础上 添加解析对应类型的函数
		/// </summary>
		static Dictionary<Type,ParseFunc> binder = new Dictionary<Type,ParseFunc>()
		{
			{typeof(Vector3),ParseVector3},
			{typeof(bool),ParseBool}
		};
		static Dictionary<Type,MethodInfo> cache = new Dictionary<Type,MethodInfo>();

		static ParseBinder()
		{
			foreach(var item in binder)
			{
				cache[item.Key] = item.Value.Method;
			}
		}
		/// <summary>
		/// 取得目标类型的Parse 函数
		/// </summary>
		/// <returns>The method.</returns>
		/// <param name="type">Type.</param>
		public static MethodInfo ParseMethod(this Type type)
		{
			MethodInfo method = null;
			if(!cache.TryGetValue(type,out method))
			{
				Type[] paramsType = { typeof(string) };
				string parseFunc = "Parse";
				method = type.GetMethod(parseFunc,paramsType);
				cache[type] = method;
			}
			return method;
		}
		/// <summary>
		/// 顶点分隔符
		/// </summary>
		private const char sp_vector3 = ',';
		public static object ParseVector3(string src)
		{
			return ParseVector3(src,sp_vector3);
		}
		public static object ParseBool(string self)
		{
			bool b = self != "0";
			return b;
		}
		public static object ParseVector3(string src,char sp)
		{
			Vector3 v = Vector3.zero;
			if(src.Equals("0"))
			{

			}
			else
			{
				string[] ss = src.Split(sp_vector3);
				if(ss.Length == 3)
				{
					v.x = float.Parse(ss[0]);
					v.y = float.Parse(ss[1]);
					v.z = float.Parse(ss[2]);
				}
				else
				{
					Debug.LogErrorFormat("parse to Vector3 error {0}",src);
				}
			}
			return v;
		}
	}
}
